<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\index\addons;

use think\facade\Db;
use think\facade\View;
use app\addons\Email;
use app\index\model\User;
/**
 * 登录组件
 */
class Login
{
    // token撒盐
    private static $salt = '513038996@qq.com';

    /**
     * 清除登录状态
     */
    public static function clearLoginStatus()
    {
        cookie('index_token', null);
        cookie('index_last_url', null);
        session('index_user', null);
    }
    
    /**
     * 获取当前ip登录错误次数
     */
    public static function getLoginErrorNum(): int
    {
        $index_error_num  = session('index_error_num');
        return empty($index_error_num) ? 0 : $index_error_num;
    }

    /**
     * 设置当前ip登录错误次数
     */
    public static function setLoginErrorNum(): void
    {
        $get_num    = self::getLoginErrorNum();
        $index_error_num  = $get_num + 1;
        session('index_error_num', $index_error_num);
    }

    /**
     * 清除当前ip登录错误次数
     */
    public static function clearLoginErrorNum(): void
    {
        session('index_error_num', null);
    }

    /**
     * 是否开启自动登录验证
     */
    public static function openAutomaticLogin(array $input): void
    {
        $userInfo = session('index_user');
        $key   = $userInfo->account . self::$salt . request()->ip();
        $token = password_hash($key, PASSWORD_BCRYPT, ['cost' => 12]);
        $time  = 14*24*3600;
        if ($input['checked']) {
            $bool = Db::name('user_token')->save([
                'user_id'     => $userInfo->id, 
                'token'       => $token, 
                'create_time' => date('Y-m-d H:i:s')
            ]);
            if ($bool) {
                cookie('index_token', $token, $time);
            }
        } else {
            cookie('index_token', null);
        }
    }

    /**
     * 根据token自动登录
     */
    public static function checkAutomaticLogin(): void
    {
        $userInfo = session('index_user');
        if (empty($userInfo)) {
            $token = cookie('index_token');
            if ($token) {
                $time   = 14*24;
                $userId = Db::name("user_token")->where("token", $token)->whereTime("create_time","-$time hours")->value('user_id');
                if ($userId) {
                    $userInfo = User::with(['group'])->where('status', 1)->where('id', $userId)->find();
                    if ($userInfo) {
                        session('index_user',$userInfo);
                    }
                }
            }
        }
    }

    /**
     * 发送邮箱验证码
     */
    public static function sendEmailCode(string $email, string $name, string $operation): array
    {
        $value = session($name);
        if (! empty($value)) {
            $interval = 60;
            $lasttime = unserialize($value)['time'];
            if (time() - $lasttime < $interval) {
                return ['status'=>'error','message' => lang('Get too frequently, please wait a minute and try again')];
            }
        }
        $title = request()->basics['seo_title'];
        $code  = rand(1000,9999);
        $body  = $operation. lang('verify') ."<br/>".lang('Hello')."".$email."!<br/>".lang('Welcome to register')." ".$title."，".lang('Please fill in the verification code on the registration page')."。<br/>".lang('verification code')."：".$code."";
        $res   = Email::send($email,$title,$body);
        if ($res['status'] === 'success') {
            $arr['code'] = $code;
            $arr['time'] = time();
            $session     = serialize($arr);
            session($name, $session);
        }
        return $res;
    }

    /**
     * 获取邮箱验证码
     */
    public static function getEmailCode(string $name): ?int
    {
        $value = session($name);
        session($name, null);
        return empty($value) ? null : unserialize($value)['code'];
    }


    /**
     * 权限验证（按需调用）
     */
    public static function authorityCheck(array $group = [])
    {
        if (!empty($group)){
            if (!empty(request()->userInfo)) {
                if (! in_array(request()->userInfo['group_id'], $group)) {
                    return request()->isPost() ? json(["status"=>"error","message"=>lang("Sorry, You don't have that right")]) : View::fetch("403");
                } else {
                    return true;
                }
            } else {
                if (request()->isGet()) {
                    cookie('index_last_url', request()->url(true));
                }
                return request()->isPost() ? json(['status'=>'login', 'message'=>'权限不足，请登录后尝试访问']) : redirect(get_url('user/login'));
            }
        } else {
            return true;
        }
    }

}